#!/bin/bash

set -x
set -e

function start()
{
    if ! pgrep -f "$1"; then
        exec "$@" &
    fi
}

function env_value()
{
    if [[ -x "/usr/bin/bash" ]]; then
        export SHELL=/bin/bash
    fi

    if [[ -x "/usr/bin/env" ]]; then
        export _=/usr/bin/env
    fi

    if [[ -x "/usr/bin/ibus-daemon" ]]; then
        export QT_IM_MODULE=ibus
        export GTK_IM_MODULE=ibus
        export XMODIFIERS="@im=ibus"
    elif [[ -x "/usr/bin/fcitx" ]]; then
        export QT_IM_MODULE=fcitx
        export GTK_IM_MODULE=fcitx
        export XMODIFIERS="@im=fcitx"
    fi
}

function start_terminator()
{
    if [[ -x /usr/bin/graceful-terminator ]]; then
        start /usr/bin/graceful-terminator
    elif [[ -x /usr/bin/terminator ]]; then
        start /usr/bin/terminator
    else
        start /usr/bin/xterm
    fi
}

# FIXME:// 此处需要通用的解决方案
# 打开双屏
start xrandr --output eDP-2 --auto --primary --output  HDMI-1-0 --auto --right-of eDP-2


# 设置 桌面背景
start feh --bg-scale /usr/share/themes/graceful-theme/wallpapers/graceful-wm-wallpaper.svg

# 导出一些环境变量
env_value

# 启动 ibus 输入法
if [[ -x "/usr/bin/ibus-daemon" ]]; then
  ibus-daemon -x -n graceful-linux -d
fi

# 启动窗口组合管理器
start /usr/bin/graceful-compton --config /etc/graceful-linux/compton.conf

# 启动 Gtk 设置
start /usr/bin/graceful-settings

# 启动锁屏
start /usr/bin/xscreensaver --no-splash

# 启动终端
# start_terminator

# 启动窗口管理器
# shellcheck disable=SC2046
while [ ! $(pgrep graceful-wm) ]; do
    /usr/bin/graceful-wm
    sleep 1
done

